<!--
 * @Author: liuxiang
 * @Date: 2022-01-20 15:46:20
 * @LastEditors: liuxiang
 * @LastEditTime: 2022-01-24 09:13:06
 * @Description: file content
-->
<template>
  <div class="Record">
    <div class="content">
      <div class="time">{{ recordTime }}</div>
      <el-tooltip class="item" effect="dark" content="停止" placement="bottom">
        <img @click="btnStopRecordClicked" src="./../assets/stop.png" alt="" />
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="继续"
        placement="top"
        v-if="isPause"
      >
        <img @click="btnGoRecordClicked" src="./../assets/begin.png" alt="" />
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="暂停"
        placement="top"
        v-if="!isPause"
      >
        <img
          @click="btnPauseRecordClicked"
          src="./../assets/pause.png"
          alt=""
        />
      </el-tooltip>
    </div>
  </div>
</template>

<script>
import fixWebmMetaInfo from "fix-webm-metainfo";
import PlayerCanvas from "../PlayerCanvas";
import moment from "moment";
import { windowClose } from "./../../main/window/Plugins";
import { timeStamp } from "console";

var SCREEN_WIDTH = window.screen.width;
var SCREEN_HEIGHT = window.screen.height;
const { desktopCapturer, remote, ipcRenderer } = require("electron");
const fs = require("fs");
const path = require("path");
var direction = path.sep;
export default {
  name: "",
  data() {
    return {
      time: 0,
      _playerCanvas: null,
      form: {},
      recordSourceId: "",
      timer: "",
      isPause: false,
    };
  },
  computed: {
    recordTime() {
      return moment(this.time * 1000)
        .utc()
        .format("HH:mm:ss");
    },
  },
  mounted() {
    this.form = this.$ElStore.get("recordForm");
    this.recordSourceId = this.$ElStore.get("recordSourceId");
    SCREEN_WIDTH = parseInt(window.screen.width * this.form.definition);
    SCREEN_HEIGHT = parseInt(window.screen.height * this.form.definition);
    this._playerCanvas = new PlayerCanvas(SCREEN_WIDTH, SCREEN_HEIGHT);
    this.btnStartRecordClicked();
    const win = remote.getCurrentWindow();
    ipcRenderer.send("recordWindow", win.id);
    ipcRenderer.on("stopRecord", () => {
      console.log("stopRecord");
      ipcRenderer.send("recordWindow", "");
      this.btnStopRecordClicked();
    });
  },
  methods: {
    formatTime(time) {
      // return time
    },
    //开始
    async btnStartRecordClicked() {
      this.timer = setInterval(() => {
        this.time++;
      }, 1000);
      this._stream = new MediaStream();
      await this.attachAudioStream();
      //this._cameraStream = await navigator.mediaDevices.getUserMedia({video: true, audio: false});

      // this._playerCanvas.setCameraVideo(
      //   this.createVideoElementWithStream(this._cameraStream)
      // );

      this._screenStream = await navigator.mediaDevices.getUserMedia({
        audio: false,
        video: {
          mandatory: {
            chromeMediaSource: "desktop",
            chromeMediaSourceId: this.recordSourceId,
            minWidth: SCREEN_WIDTH,
            minHeight: SCREEN_HEIGHT,
          },
        },
      });
      //设置屏幕流
      this._playerCanvas.setScreenVideo(
        this.createVideoElementWithStream(this._screenStream)
      );
      //将canvas转为流
      let playerCanvasStream = this._playerCanvas.canvas.captureStream();
      playerCanvasStream.getTracks().forEach((t) => this._stream.addTrack(t));
      //this.$refs.preview.srcObject = playerCanvasStream;

      //开始保存文件
      this.startRecord();
    },
    //获取音频
    async attachAudioStream() {
      let self = this;
      if (this.form.voiceType === "microphone") {
        //麦克风音频
        this._audioStream = await navigator.mediaDevices.getUserMedia({
          video: false,
          audio: true,
        });
        this._audioStream
          .getAudioTracks()
          .forEach((value) => this._stream.addTrack(value));
      } else {
        //系统音频
        let sources = await desktopCapturer.getSources({ types: ["screen"] });
        try {
          self._audioStream = await navigator.mediaDevices.getUserMedia({
            video: {
              mandatory: {
                // cursor:"never",
                chromeMediaSource: "desktop",
              },
            },
            audio: {
              mandatory: {
                chromeMediaSource: "desktop",
              },
            },
          });
          self._audioStream
            .getAudioTracks()
            .forEach((value) => self._stream.addTrack(value));
        } catch (err) {
          console.log(err);
        }
      }
    },
    //创建视频流容器
    createVideoElementWithStream(stream) {
      let video = document.createElement("video");
      video.autoplay = true;
      video.srcObject = stream;
      return video;
    },
    // 停止
    btnStopRecordClicked() {
      clearInterval(this.timer);
      this.recording = false;
      this._recorder.stop();
    },
    startRecord() {
      this._recorder = new MediaRecorder(this._stream, {
        mimeType: "video/webm;codecs=h264",
      });
      // 停止录屏时触发文件保存事件
      this._recorder.start();
      this.recording = true;

      var _this = this;
      this._recorder.ondataavailable = async (e) => {
        let isExist = fs.existsSync(this.form.saveDir);
        if (!isExist) {
          // 没有该文件或目录则创建
          fs.mkdirSync(this.form.saveDir);
        }
        let reader = new FileReader();
        reader.onload = function () {
          var buffer = new Buffer(reader.result);
          let name = moment().format("YYYYMMDD_HHmmss");
          console.log(
            _this.form.saveDir + direction + name + ".webm",
            '_this.form.saveDir + direction + name + ".webm"'
          );
          // temp文件夹应已存在
          fs.writeFileSync(
            _this.form.saveDir + direction + name + ".webm",
            buffer
          );
          const win = remote.getCurrentWindow();
          win.getParentWindow().show();
          windowClose(win.id);
        };
        let newBlob = await fixWebmMetaInfo(e.data);
        reader.readAsArrayBuffer(newBlob); // 假设blob已定义,且为MP4视频
      };
    },

    // 继续
    btnGoRecordClicked() {
      this.isPause = false;
      this.btnStartRecordClicked();
    },

    // 暂停
    btnPauseRecordClicked() {
      this.isPause = true;
      clearInterval(this.timer);
      this._recorder.pause();
    },
  },
};
</script>
<style lang="scss" scoped>
.Record {
  width: 100%;
  height: 100vh;
  -webkit-app-region: drag;
  padding: 20px;
  box-sizing: border-box;
  .content {
    float: left;
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 50px;
    padding: 0 20px;
    height: 60px;
    border: 1px solid red;
    .time {
      font-size: 20px;
    }
    img {
      width: 50px;
      margin-left: 10px;
      -webkit-app-region: no-drag;
    }
  }
}
</style>
